<?php defined('PATH') or exit();

class Model_News extends SimpleO {

	private $data = array('id' => null, 'title' => null, 'body' => null, 'time' => null, 'comments' => null);

	public function __construct() {
		parent::__construct();
	}

	public function load($_id) {
		$this->data = $this->db->query('SELECT *, (SELECT COUNT(*) FROM `__archez_comments` WHERE `__archez_comments`.`news_id` = `__archez_news`.`id`) as `comments` FROM `__archez_news` WHERE `__archez_news`.`id` = '.$this->db->quote($_id))->fetch();
		if ($this->data) {
			return true;
		}
		return false;
	}

	public function __get($_key) {
		if (is_array($this->data) && array_key_exists($_key, $this->data))
			return $this->data[$_key];
	}

	public function __set($_key, $_value) {
		if (is_array($this->data) && array_key_exists($_key, $this->data))
			$this->data[$_key] = $_value;
	}

	public function save() {
		if ($this->id)
			return (bool) $this->db->query('UPDATE `__archez_news` SET `title` = '.$this->db->quote($this->title).' AND `body` = '.$this->db->quote($this->body).' AND `time` = '.$this->db->quote($this->time));
		$this->db->query('INSERT INTO `__archez_news` (`title`, `body`, `time`) VALUES ('.$this->db->quote($this->title).', '.$this->db->quote($this->body).', '.time().')');
		$id = $this->db->lastInsertId();
		if ($id) {
			$this->id = $id;
			return true;
		}
		return false;
	}

	public function delete() {
		if ($this->id) {
			 $this->db('DELETE FROM `__archez_news` WHERE `id` = '.$this->db->quote($_id));
			 return true;
		}
		return false;
	}

	public function isLoaded() {
		if ($this->id) {
			return true;
		}
		return false;
	}

}
?>